package models;

import play.*;
import play.data.binding.As;
import play.data.validation.Required;
import play.db.jpa.*;
import play.modules.search.*;

import javax.persistence.*;

import java.util.*;

@Indexed
@Entity
public class Lecture extends Model {
    
	@Field
	@Required
	public String name;
	
	@Field
	@As("yyyy-MM-dd")
    public Date date;
	
	@ManyToOne 
	public Course course;
	
	@OneToMany(mappedBy="lecture", cascade=CascadeType.ALL)
	public List<Comment> comments;
	
	@OneToMany(mappedBy="lecture", cascade=CascadeType.ALL)
	public List<Question> questions;
	
	@OneToMany(mappedBy="lecture", cascade=CascadeType.ALL)
    public List<Vote> votes;
	
	//Constructor
	public Lecture(Course course, String name, Date date) {
		this.name = name;
		this.course = course;
		this.date = date;
		create();
	}
	
	//Different Comment handlers
	
	/**
	 * Comment on a Lecture
	 */
	public Comment comment(User by, String content) {
		return new Comment(this, by, content);
	}
	
	/**
	 * Find all Comments for this lecture
	 */
	public List<Comment> getComments() {
        return Comment.find("lecture = ? order by postedAt asc", this).fetch();
    }
	
	public Long getCommentCount() {
		return Comment.count("lecture", this);
	}
	
	/**
	 * Find all Questions for this lecture
	 */
	public List<Question> getQuestions() {
		return Question.find("lecture = ? order by title asc", this).fetch();
	}
	
	public Long getQuestionCount() {
		return Question.count("lecture", this);
	}
	
	/**
	 * Count how many different users commented
	 */
	public Long getVoicesCount() {
        return User.count("select count(distinct u) from User u, Lecture l, Comment c where c.postedBy = u and c.lecture = l and l = ?", this);
    }
	
	public Comment getLastComment() {
		return Comment.find("lecture = ? order by postedAt desc", this).first();
	}
	
	/**
	 * Some vote handling
	 */
	//Get number of upvotes for a specific lecture
    public long getUpvoteCount() {
    	return Vote.count("lecture = ? and positive = true", this);
    }
    
  //Get number of downvotes for a specific lecture
    public  long getDownvoteCount() {
    	return Vote.count("lecture = ? and positive = false", this);
    }
}
